//
//  UserAccount.swift
//  weibo 666
//
//  Created by mac on 15/11/7.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    
//    用于调用access_token，接口获取授权后的access token。
    var access_token: String?
//    access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0{
        didSet {
//            j计算过期时间
            expriesDate = NSDate(timeIntervalSinceNow: expires_in)
            
        }
    }
//    当前授权用户的UID。
    var uid: String?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
//    过期日期
    var expriesDate: NSDate?
    
    init(dict: [String: AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let keys = ["access_token","uid","expriesDate","expires_in","screen_name","avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    //MARK: - 保存对象
    func saveUserAccount() {
        
        //保存路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        print(path)
        
        //保存归档
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    ///归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expriesDate, forKey: "expriesDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    ///解档
    // `required` - 没有继承性，所有的对象只能解档出当前的类对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expriesDate = aDecoder.decodeObjectForKey("expriesDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}

